package com.ken.work.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import javax.imageio.stream.FileImageInputStream;

import org.apache.commons.lang.StringUtils;

public class StringUtil extends StringUtils {
	public static String toHexString1(int val) {
		String rs = Integer.toHexString(val);
		if (rs.length() < 2) {
			rs = "0" + rs;
		}
		return rs;
	}

	public static String getCharAndNumr(int length) {
		String val = "";

		Random random = new Random();
		for (int i = 0; i < length; i++) {
			String charOrNum = random.nextInt(2) % 2 == 0 ? "num" : "num"; // 输出字母还是数字

			if ("char".equalsIgnoreCase(charOrNum)) // 字符串
			{
				int choice = 97; // 取得大写字母还是小写字母
				val += (char) (choice + random.nextInt(6));
			} else if ("num".equalsIgnoreCase(charOrNum)) // 数字
			{
				val += String.valueOf(random.nextInt(10));
			}
		}

		return val;
	}

	public static String BytesHexString(byte[] b) {
		String ret = "";
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			ret += hex.toUpperCase();
		}
		return ret;
	}

	public static String getByteString(byte[] val) {
		if (val == null || val.length < 1)
			return "";
		String s = "";
		for (byte vl : val)
			s = s + " " + (vl + "");
		return s;

	}

	public static String readBytes(String FilePath) {
		File file = new File(FilePath);
		BufferedReader reader = null;
		String retString = "";
		String tempString = "";
		try {
			reader = new BufferedReader(new FileReader(file));
			while ((tempString = reader.readLine()) != null) {
				retString=retString+tempString;
			}
			reader.close();
		} catch (IOException e) {
			
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return retString;

	}

	public static byte[] readImageBytes(File aFile) {
		FileImageInputStream input = null;
		ByteArrayOutputStream out = null;
		try {
			input = new FileImageInputStream(aFile);
			byte[] temp = new byte[(int) (input.length() < 1024 ? input
					.length() : 1024)];
			out = new ByteArrayOutputStream();
			int size = 0;

			while ((size = input.read(temp)) != -1) {
				out.write(temp, 0, size);
			}
			byte[] retVal = out.toByteArray();
			return retVal;

		} catch (Exception err) {
		} finally {
			try {
				input.close();
			} catch (IOException e) {
			}
			try {
				out.close();
			} catch (IOException e) {
			}
		}
		return null;
	}
}
